package com.gewu.pm.ui.activity.delivery;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.ui.activity.filter.FilterMultipleActivity;
import com.gewu.pm.ui.adapter.delivery.DeliveryTerminalAdapter;
import com.gewu.pm.ui.popup.SelectTimePopup;
import com.gewu.pm.widget.FilterBar;
import com.hjq.base.BaseAdapter;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 配送管理（终端）
 */
public final class DeliveryManagementTerminalActivity extends AppActivity
        implements OnRefreshLoadMoreListener, BaseAdapter.OnItemClickListener {

    private FilterBar mFilterBar;
    private LinearLayout mDateFilterLayout;
    private TextView mDateFilterTextView;
    private EditText mSearchEdit;
    private SmartRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;

    private DeliveryTerminalAdapter mAdapter;

    private int mPageNumber = 1;  // 当前页码
    private static final int PAGE_SIZE = 10;  // 每页数量

    private List<String> mAllDataList = new ArrayList<>();  // 全部数据
    private String mSearchKeyword = "";  // 搜索关键词
    private String mCurrentDateFilter = "今日";  // 当前日期筛选

    public static void start(Context context) {
        Intent intent = new Intent(context, DeliveryManagementTerminalActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.delivery_management_terminal_activity;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mFilterBar = findViewById(R.id.filter_bar);
        mRefreshLayout = findViewById(R.id.srl_refresh);
        mRecyclerView = findViewById(R.id.rv_list);

        // 获取 FilterBar 中的控件
        mDateFilterLayout = mFilterBar.getDateFilterLayout();
        mDateFilterTextView = mFilterBar.getDateFilterTextView();
        mSearchEdit = mFilterBar.getSearchEditText();

        // 设置 RecyclerView
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new DeliveryTerminalAdapter(this);
        mAdapter.setOnItemClickListener(this);
        mRecyclerView.setAdapter(mAdapter);

        // 设置刷新监听
        mRefreshLayout.setOnRefreshLoadMoreListener(this);

        // 设置搜索监听
        mSearchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                mSearchKeyword = s.toString().trim();
                loadData(true);
            }
        });

        // 设置点击事件
        setOnClickListener(mDateFilterLayout);
    }

    @Override
    protected void initData() {
        // 创建测试数据
        createTestData();
        
        // 加载第一页数据
        loadData(true);
    }

    /**
     * 创建测试数据
     */
    private void createTestData() {
        mAllDataList.clear();
        
        String[] terminalNames = {
            "落落超市",
            "银泰大厦便利店",
            "西湖区小卖部",
            "滨江商贸中心",
            "下沙大学城超市",
            "萧山区连锁店",
            "余杭区便利店",
            "拱墅区小商铺",
            "上城区零售店",
            "江干区批发部",
            "富阳区商行",
            "临安区超市",
            "桐庐县门店",
            "建德市零售部",
            "淳安县商店"
        };
        
        mAllDataList.addAll(Arrays.asList(terminalNames));
    }

    /**
     * 加载数据
     */
    private void loadData(boolean isRefresh) {
        if (isRefresh) {
            mPageNumber = 1;
        }
        
        // 根据搜索关键词过滤数据
        List<String> filteredList = filterData();
        
        // 分页获取数据
        int startIndex = (mPageNumber - 1) * PAGE_SIZE;
        int endIndex = Math.min(startIndex + PAGE_SIZE, filteredList.size());
        
        // 创建新的List副本，避免ConcurrentModificationException
        List<String> pageData = new ArrayList<>();
        if (startIndex < filteredList.size()) {
            for (int i = startIndex; i < endIndex; i++) {
                pageData.add(filteredList.get(i));
            }
        }
        
        // 更新列表
        if (isRefresh) {
            mAdapter.setData(pageData);
            if (mRefreshLayout.isRefreshing()) {
                mRefreshLayout.finishRefresh();
            }
        } else {
            mAdapter.addData(pageData);
            mRefreshLayout.finishLoadMore();
        }
        
        // 判断是否还有更多数据
        if (endIndex >= filteredList.size()) {
            mRefreshLayout.setNoMoreData(true);
        }
    }

    /**
     * 根据关键词过滤数据
     */
    private List<String> filterData() {
        if (mSearchKeyword.isEmpty()) {
            return mAllDataList;
        }
        
        List<String> result = new ArrayList<>();
        for (String terminalName : mAllDataList) {
            if (terminalName.contains(mSearchKeyword)) {
                result.add(terminalName);
            }
        }
        return result;
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view == mDateFilterLayout) {
            // 日期筛选弹窗
            showDateFilterPopup();
        }
    }

    /**
     * 显示日期筛选弹窗
     */
    private void showDateFilterPopup() {
        List<String> dateList = Arrays.asList("今日", "7天", "一个月");

        SelectTimePopup.Builder builder = new SelectTimePopup.Builder(this)
                .setList(dateList)
                .setSelectedItem(mCurrentDateFilter)
                .setListener((popupWindow, category) -> {
                    mCurrentDateFilter = category;
                    mDateFilterTextView.setText(category);
                    
                    // 刷新数据
                    loadData(true);
                });
        
        builder.showAsDropDown(mDateFilterLayout);
    }

    @Override
    public void onRightClick(View view) {
        super.onRightClick(view);
        // 跳转到筛选页面
        FilterMultipleActivity.start(this);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        // 下拉刷新
        loadData(true);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        // 上拉加载更多
        mPageNumber++;
        loadData(false);
    }

    @Override
    public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
        String terminalName = mAdapter.getItem(position);
        toast("点击终端：" + terminalName);
        // TODO: 跳转到终端详情页
    }
}

